# -*- encoding: utf-8 -*-
"""
File Name: dedicated_line_monitor
Description:
Author : 'lirui'
date: 2024/1/26
Contact: marjey_lee@163.com
Change Activity:
2024/1/26:
"""
import time

import ll
from projects.monitoring.branch_dedicated_line_monitor.services.cli_parse import CliParser
from projects.monitoring.branch_dedicated_line_monitor.utils.router_connection import build_router_connection_mapping


class LoadYunnanBranchLineStatus:
    def __init__(self):
        super().__init__()
        self.results = {}
        self.normal_ips = []
        self.error_ips = []
        self.running_success = True
        self.router_connection_mapping = build_router_connection_mapping()

    def run(self):
        ll.get_logger().info('Start monitoring branch dedicated line.')
        while True:
            try:
                self()
            except Exception as e:
                ll.get_logger().error(e)
            time.sleep(30)

    def format_results(self, normal_ip_lst, error_ip_lst):
        """

        Args:
            normal_ip_lst:
            error_ip_lst:

        Returns:

        """
        for ip in normal_ip_lst:
            self.results[ip] = 1
            self.normal_ips.append(ip)
        for ip in error_ip_lst:
            self.results[ip] = 0
            self.error_ips.append(ip)

    def __call__(self):
        """
        monitor dedicated line
        """
        ll.get_logger().info('Start monitor branch dedicated line.')
        cmd = 'display  bgp vpnv4 vpn-instance FDBANK peer'
        error_ip_lst = []
        normal_ip_lst = []
        try:
            for name, connection in self.router_connection_mapping.items():
                res = connection.send_command(
                    cmd,
                    read_timeout=20
                )
                normal_ips, error_ips = CliParser(res)()
                assert (len(normal_ips) > 0 or len(error_ips) > 0)
                error_ip_lst = error_ips + error_ip_lst
                normal_ip_lst = normal_ip_lst + normal_ips
            self.format_results(normal_ip_lst, error_ip_lst)
        except Exception as e:
            ll.get_logger().error(e)
            self.running_success = False
        finally:
            self.disconnection()

    def disconnection(self):
        try:
            for router, v in self.router_connection_mapping.items():
                v.disconnect()
        except Exception as e:
            self.running_success = False
            ll.get_logger().error(e)


def _main():
    monitor = LoadYunnanBranchLineStatus()
    monitor()


if __name__ == '__main__':
    _main()
